package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerAccept extends PublicThread {
	private MainClientThread mainClient = null;

	public ServerAccept(ServerSocket serversocket, ThreadPool threadPool) {
		this.serverSocket = serversocket;
		this.threadPool = threadPool;
		addToThreadPool();
	}

	public void run() {
		ServerThread server = null;
		ClientThread client = null;
		Socket socket = null;
		try {
			while (isRun) {
				if (mainClient.isConnect()) {
					
					System.out.println("Waiting Server Connect, Port: " + serverSocket.getLocalPort());
					socket = serverSocket.accept();
					System.out.println("new Server Connect, Address: " + socket.getInetAddress().getHostAddress()
							+ ", Port: " + socket.getPort());

					server = new ServerThread(socket, threadPool);
					client = new ClientThread(new ServerSocket(0), threadPool);
					
					server.setClient(client);
					client.serServer(server);
					
					client.newThreadStrat();
					mainClient.send(("NewPort " + client.getPort() + ",").getBytes());
				}
				sleep(100);
			}
		} catch (IOException e) {
			System.out.print("AcceptThread Error" + e.getMessage());
		}
		close();
		removeFromThreadPool();
	}

	public void close() {
		try {
			super.closeThread();
		} catch (Exception e1) {
			System.out.print("close ServerAccept socket Error, Port:" + serverSocket.getLocalPort());
		}
	}

	public void setMainClient(MainClientThread client) {
		this.mainClient = client;
	}
}
